package com.myccb.app;

import  android.annotation.SuppressLint;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.myccb.app.base.BaseActivity;
import com.myccb.app.base.ViewPagerAdapter;
import com.myccb.app.view.investment.InvestmentFragment;
import com.myccb.app.view.activity.LoginActivity;
import com.myccb.app.view.activity.MenuItemActivity;
import com.myccb.app.view.fragment.CreditCardFragment;
import com.myccb.app.view.fragment.IndexFragment;
import com.myccb.app.view.fragment.LifeFragment;
import com.myccb.app.view.fragment.LoanFragment;

import java.lang.reflect.Field;

public class MainActivity extends BaseActivity {

    private BottomNavigationView bottom_navigation;
    private DrawerLayout drawerLayout;
    private NavigationView nav_view;
    private MenuItem prevMenuItem;
    private ViewPager container;
    private CoordinatorLayout mainLayout;
    private TextView title;
    private TextView searchBar;
    private Toolbar toolbar;
    private ImageView navMenuButton;

    private TextView tv_clickToLogin;
    private ImageView iv_clickToLogin;
    private TextView lastLoginTimeView;
    private TextView logoutBtn;
    private TextView userNameView;

    private LinearLayout loginInfoLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AppStatus.isLogin){
            loginInfoLayout.setVisibility(View.VISIBLE);
            userNameView.setText(AppStatus.getInstance().getSavedUserName());
            lastLoginTimeView.setVisibility(View.VISIBLE);
            lastLoginTimeView.setText("登录时间 "+AppStatus.lastLoginTime);
            tv_clickToLogin.setVisibility(View.INVISIBLE);
        }else {
            loginInfoLayout.setVisibility(View.INVISIBLE);
            lastLoginTimeView.setVisibility(View.INVISIBLE);
            tv_clickToLogin.setVisibility(View.VISIBLE);
        }
    }

    private void initView() {
        bottom_navigation = findViewById(R.id.bottom_navigation);
        container = findViewById(R.id.container);
        drawerLayout = findViewById(R.id.drawer_layout);
        nav_view = findViewById(R.id.nav_view);
        mainLayout = findViewById(R.id.main_layout);
        toolbar = findViewById(R.id.toolbar);
        title = findViewById(R.id.toolbarTitle);
        searchBar = findViewById(R.id.toolbarSearch);
        navMenuButton = findViewById(R.id.toolbar_menu_button);

        setSupportActionBar(toolbar);

        ViewGroup.LayoutParams params = nav_view.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels * 2 / 3;
        nav_view.setLayoutParams(params);
        nav_view.setItemIconTintList(null);

        initNavView();

        disableShiftMode(bottom_navigation);
        bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                //current_tab=item.getItemId();
                switchToolbarContent(item.getItemId());
                switch (item.getItemId()) {
                    case R.id.item_index:
                        container.setCurrentItem(0);
                        break;
                    case R.id.item_credit_card:
                        container.setCurrentItem(1);
                        break;
                    case R.id.item_investment:
                        container.setCurrentItem(2);
                        break;
                    case R.id.item_loan:
                        container.setCurrentItem(3);
                        break;
                    case R.id.item_life:
                        container.setCurrentItem(4);
                }
                return true;
            }
        });

        container.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            private int count = 0;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position == 0 && positionOffset == 0.0 && positionOffsetPixels == 0)
                    count++;
                else
                    count = 0;
                if (count > 2)
                    drawerLayout.openDrawer(Gravity.LEFT, true);
            }

            @Override
            public void onPageSelected(int position) {
                if (prevMenuItem != null) {
                    prevMenuItem.setChecked(false);
                } else {
                    bottom_navigation.getMenu().getItem(0).setChecked(false);
                }
                bottom_navigation.getMenu().getItem(position).setChecked(true);
                prevMenuItem = bottom_navigation.getMenu().getItem(position);
                switchToolbarContent(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        setupViewPager(container);

        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                //获取屏幕的宽高
                mainLayout.setX(nav_view.getWidth()+nav_view.getX());
               /* WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                Display display = manager.getDefaultDisplay();
                mainLayout.layout(nav_view.getRight(), 0, nav_view.getRight() + display.getWidth(), display.getHeight());*/
            }

            @Override
            public void onDrawerOpened(View drawerView) {}

            @Override
            public void onDrawerClosed(View drawerView) {
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        navMenuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });
        switchToolbarContent(0);
    }

    private void initNavView() {
        View headerView=nav_view.getHeaderView(0);

        tv_clickToLogin=headerView.findViewById(R.id.click_to_login_tv);
        iv_clickToLogin=headerView.findViewById(R.id.click_to_login_iv);
        lastLoginTimeView=headerView.findViewById(R.id.last_login_time);
        userNameView=headerView.findViewById(R.id.username_textview);
        logoutBtn=headerView.findViewById(R.id.logout_btn);
        loginInfoLayout=headerView.findViewById(R.id.login_info_layout);

        iv_clickToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppStatus.isLogin){

                }
                else {
                    Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                    startActivity(intent);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                }
            }
        });
        tv_clickToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
                drawerLayout.closeDrawer(Gravity.LEFT);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });

        logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppStatus.isLogin=false;
                drawerLayout.closeDrawer(Gravity.LEFT);
                onResume();
                IndexFragment.getInstance().onResume();
                CreditCardFragment.getInstance().onResume();
                InvestmentFragment.getInstance().onResume();
                LoanFragment.getInstance().onResume();
                LifeFragment.getInstance().onResume();
            }
        });
        nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                MenuItemActivity.launchMenuLayout(item.getItemId(),MainActivity.this);
                return false;
            }
        });
    }

    private void switchToolbarContent(int index) {
        switch (index) {
            case 0:
                title.setVisibility(View.INVISIBLE);
                searchBar.setVisibility(View.VISIBLE);
                searchBar.setText("搜索");
                break;
            case 1:
                title.setVisibility(View.VISIBLE);
                searchBar.setVisibility(View.INVISIBLE);
                title.setText("信用卡");
                break;
            case 2:
                title.setVisibility(View.VISIBLE);
                searchBar.setVisibility(View.INVISIBLE);
                title.setText("投资理财");
                break;
            case 3:
                title.setVisibility(View.VISIBLE);
                searchBar.setVisibility(View.INVISIBLE);
                title.setText("贷款");
                break;
            case 4:
                title.setVisibility(View.INVISIBLE);
                searchBar.setVisibility(View.VISIBLE);
                searchBar.setText("水费");
        }
    }
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(IndexFragment.getInstance());
        adapter.addFragment(CreditCardFragment.getInstance());
        adapter.addFragment(InvestmentFragment.getInstance());
        adapter.addFragment(LoanFragment.getInstance());
        adapter.addFragment(LifeFragment.getInstance());
        viewPager.setAdapter(adapter);
    }
    @SuppressLint("RestrictedApi")
    private void disableShiftMode(BottomNavigationView navigationView) {
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) navigationView.getChildAt(0);
        try {
            Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
            shiftingMode.setAccessible(true);
            shiftingMode.setBoolean(menuView, false);
            shiftingMode.setAccessible(false);
            for (int i = 0; i < menuView.getChildCount(); i++) {
                BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(i);
                itemView.setShiftingMode(false);
                itemView.setChecked(itemView.getItemData().isChecked());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //再按一次退出
    private long exitTipTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK){
        if (System.currentTimeMillis() - exitTipTime <= 2000){
            return super.onKeyDown(keyCode, event);
        }
        else {
            exitTipTime = System.currentTimeMillis();
            Toast.makeText(this, "再按一次退出建设银行app！", Toast.LENGTH_SHORT).show();
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
    }
}